<template>
  <keep-alive>
    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="工单号">
                  <a-input v-model:value="queryParam.woid" allow-clear :disabled="allDis" />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="7" :md="8" :sm="24">
                <a-form-item label="产品或产品组">
                  <j-popup placeholder="请选择产品或产品组" v-model="queryParam.partno" code="partno_pop"
                           org-fields="partno" dest-fields="partno" :field="getPopupField('partno')" :multi="true" :disabled="allDis" />
                </a-form-item>
              </a-col>
<!--              <a-col :xl="4" :lg="7" :md="8" :sm="24">-->
<!--                <a-form-item label="处理维度">-->
<!--                  <a-select-->
<!--                    ref="select"-->
<!--                    v-model="queryParam.typ"-->
<!--                    placeholder="请选择处理维度"-->
<!--                    :disabled="allDis"-->
<!--                  >-->
<!--                    <a-select-option :value="null">请选择</a-select-option>-->
<!--                    <a-select-option value="1">产品</a-select-option>-->
<!--                    <a-select-option value="2">盒</a-select-option>-->
<!--                    <a-select-option value="3">箱</a-select-option>-->
<!--                  </a-select>-->
<!--                </a-form-item>-->
<!--              </a-col>-->
              <a-col :md="8" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="allDisabled">锁定</a-button>
              <a-button type="primary" @click="openDisabled" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域 -->
        <div class="components-input-demo-size">
          <a-input v-model:value="val" size="large" placeholder="请输入产品码" @keyup.enter="enterData" />
        </div>
      </a-card>
    </a-spin>
  </keep-alive>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { downFile, getAction, httpAction } from '@/api/manage'
import OpSelect from '@comp/mes/OpSelect.vue'
import '@/assets/less/TableExpand.less'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'

export default {
  barcode: '',
  name: 'BatchUnbindEntry',
  mixins: [JeecgListMixin],
  components: {
    OpSelect
  },
  data() {
    return {
      description: '批量不良录入',
      title: '操作',
      label: '',
      remark: '',
      val: '',
      oldwoid:'',
      opOptions: [],
      cfgOptions: [],
      cfgOptionDetails: [],
      rwkOptions: [],
      visible: false,
      allDis: false,
      confirmLoading: false,
      logs: [],
      fixedColumns: [
        {
          width: '10%',
          align: 'left',
          dataIndex: 'time'
        },
        {
          width: '90%',
          align: 'left',
          dataIndex: 'msg'
        }
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      validatorRules: {
        code: [
          { required: true, message: '请选择方案!' }
        ]
      },
      // 表头
      queryParam: {
        unitsn: this.$route.query.unitsn
      },
      isNok: false,
      oneLoad: 1,
      leftWidth: '65%',
      rightWidth: '35%',
      columns: [
        {
          title: '工单ID',
          align: 'center',
          dataIndex: 'woid'
        },
        {
          title: '序列号',
          align: 'center',
          dataIndex: 'unitsn'
        },
        {
          title: '产品码',
          align: 'center',
          dataIndex: 'product'
        },
        {
          title: '产品或产品组',
          align: 'center',
          dataIndex: 'partno'
        },
        {
          title: '产线或产线组',
          align: 'center',
          dataIndex: 'line'
        },
        {
          title: '工位',
          align: 'center',
          dataIndex: 'op'
        },
        {
          title: '工站',
          align: 'center',
          dataIndex: 'stn'
        },
        {
          title: '盒号',
          align: 'center',
          dataIndex: 'lotno',
          scopedSlots: { customRender: 'lotno' }
        },
        {
          title: '日期',
          align: 'center',
          dataIndex: 'dt',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '结果',
          align: 'center',
          dataIndex: 'result_dictText'
        },
        {
          title: '重复加工次数',
          align: 'center',
          dataIndex: 'repeatCount'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText'
        },
        {
          title: '班次日期',
          align: 'center',
          dataIndex: 'shiftDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'shift'
        },
        {
          title: '产线类型',
          align: 'center',
          dataIndex: 'segmentCode_dictText'
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'ctime'
        }
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   align: 'center',
        //   fixed: 'right',
        //   width: 147,
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      url: {
        list: '/trace/packageTrace/unbind',
        rwkList: '/qis/mesRwkCodeCfg/list',
        cfgList: '/qis/qisReinspectCfg/list',
        getOpSelect: '/basic/mesLineOpCfg/opSelect',
        exportXlsUrl: '/trace/barcodeTrace/exportXls'
      },
      runCmd: '/monitor/api/runCmd',
      dictOptions: {},
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      selectedMainId: '',
      line: '',
      op: '',
      procDataMainId: '',
      tabsModel: '1',
      superFieldList: []
    }
  },
  created() {
    console.log('页面初始化666')
    // this.getSuperFieldList()
  },
  computed: {

    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }

  },
  watch: {
    line(val) {
      console.log('产线改变')
      if (val) {
        getAction(this.url.getOpSelect, { line: val }).then((res) => {
          if (res.success) {
            this.opOptions = res.result
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.opOptions = []
        this.value = ''
      }
    }
  },
  methods: {
    refreshData(val) {
      this.$forceUpdate()
    },
    remarkChange(val) {
      let unicode = ''
      for (let i = 0; i < val.length; i++) {
        const charCode = val[i].charCodeAt(0).toString(16) // 获取每个字符的 Unicode 编码值
        if (charCode.length >= 4) {
          unicode += '\\u' + charCode // 对于超过四位的 Unicode 编码值需要添加 \u 前缀
        } else {
          unicode += '\\u00' + charCode // 对于不足四位的 Unicode 编码值需要补零
        }
      }
      this.remark = unicode
    },
    tableRowClass(record, index) {
      return 'log-' + record.level
    },
    getLog() {
      // console.log('获取日志')
      // const that = this
      // this.stnStatus = {
      //   serviceid: 'mes',
      //   cmd: 'LineStatus',
      //   Client: that.model.line,
      //   entityid: that.model.line,
      //   clientid: that.model.line,
      //   log: 0,
      //   llog: 1
      // }
      // httpAction(this.runCmd, this.stnStatus, 'post').then((res) => {
      //   if (res.success) {
      //     let log = JSON.parse(res.result.data.llog)
      //     this.logs = log
      //   } else {
      //   }
      // }).finally(() => {
      //   console.log('日志')
      //   console.log(this.logs)
      //   that.confirmLoading = false
      // })
    },
    enterData() {
      const that = this
      if (this.val.split(';').length > 1) {
        let arr = this.val.split(';')
        this.val = arr[arr.length - 2]
      } else if (this.val.split('  ').length > 1) {
        let arr = this.val.split('  ')
        this.val = arr[arr.length - 2]
      } else {
      }
      // if (this.queryParam.typ==='1'){
      //   if (this.val.split(';').length > 1) {
      //     let arr = this.val.split(';')
      //     this.val = arr[arr.length - 2]
      //   } else if (this.val.split('  ').length > 1) {
      //     let arr = this.val.split('  ')
      //     this.val = arr[arr.length - 2]
      //   } else {
      //   }
      // }else{
      //   if (that.val.split('|').length > 1) {
      //     let code = that.val.split('|')
      //     this.val =  code[0] + '|' + code[4] + '|' + code[5]
      //     this.oldwoid = code[2]
      //   } else {
      //     this.$message.error('请输入正确的箱码!')
      //   }
      // }
      that.confirmLoading = true
      getAction(this.url.list, { unitsn: this.val,woid: this.queryParam.woid,partno: this.queryParam.partno,typ: '1',oldWo: this.oldwoid }).then((res) => {
        if (res.success) {
          this.$message.success('修改成功！')
        } else {
          this.$message.warning(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        that.val = ''
        this.loading = false
        that.confirmLoading = false
      })
    },
    sendRunCmd(code) {
      const that = this
      that.confirmLoading = true
      getAction(this.url.list, { lotNo: code ,woid: code,partno: code}).then((res) => {
        if (res.success) {
          this.$message.success('修改成功！')
        } else {
          this.$message.warning(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
        that.confirmLoading = false
      })

    },
    allDisabled() {
      this.allDis = true
    },
    openDisabled() {
      this.queryParam =  {}
      this.allDis = false
      this.val = ''
    },
    opChange(val) {
      //清空下边所有选项
      this.model.cfgid = ''
      this.model.typ = null
      this.model.code = null
      this.op = val
      //访问对应产线对应工站的所有故障描述并展示
      let param = {
        line: this.model.line,
        op: this.op,
        pageNo: 1,
        pageSize: 100
      }
      getAction(this.url.cfgList, param).then((res) => {
        //将数据存放在数组中
        let option = []
        res.result.records.map(item => {
          option.push({
            value: item.recId,
            label: item.description
          })
        })
        this.cfgOptions = option
        this.cfgOptionDetails = res.result.records
      })
      //请求对应返工代码
      this.getRwkList('')
    },
    handleChange(value) {
      console.log('当前typ')
      console.log(this.model.typ)
      this.model.typ = ''
      this.model.code = ''
      let val = ''
      this.cfgOptionDetails.map(item => {
        if (item.recId === value) {
          if (item.type) {
            this.model.typ = item.type + ''
            this.getRwkList(item.type)
          } else {
            this.getRwkList('')
          }
        }
      })
      console.log('当前typ')
      console.log(this.model.typ)
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.indexOf(input) !== -1
    },
    openRework(record) {
      this.visible = true
      console.log('打开返工弹窗')
      console.log(this.dataSource)
      this.model.line = this.dataSource[0].line
      this.label = '返工'
    },
    getRwkList(typ) {
      console.log('查看op')
      console.log(this.op)
      let param = {
        line: this.model.line,
        op: this.op,
        pageNo: 1,
        pageSize: 100
      }
      if (typ) {
        param.type = typ
      }
      this.$set(this.model, 'code', '')
      getAction(this.url.rwkList, param).then((res) => {
        this.rwkOptions = res.result.records
        if (this.rwkOptions.length === 1) {
          this.$set(this.model, 'code', this.rwkOptions[0].code)
        }
      })
    },
    handleOk() {
      this.load = {
        serviceid: 'mes',
        cmd: 'rework',
        entityid: this.selectedMainId,
        clientid: this.model.line + ';;',
        code: this.model.code
      }
      httpAction(this.runCmd, this.load, 'post').then((res) => {
        console.log('返回结果')
        console.log(res)
        if (res.success) {
          this.isResult = this.product.result
        } else {
          this.isResult = this.product.result
        }
      }).finally(() => {
        this.rwkOptions = []
        this.visible = false
      })

    },
    handleCancel() {
      this.rwkOptions = []
      this.op = ''
      this.model = {}
      this.visible = false
    },
    clickLotNo(val) {
      this.$router.push({ path: './MesLotStatusList', query: { lotNo: val } })
    },
    typeChange(val) {
      if (!this.model.op) {
        this.$message.warning('请先选择工站！')
        return
      }
      if (val) {
        console.log(val)
        this.getRwkList(val)
      }
    },
    initDictConfig() {
    },
    searchQuery() {
      if (this.queryParam.unitsn.split(';').length > 1) {
        let arr = this.queryParam.unitsn.split(';')
        this.queryParam.unitsn = arr[arr.length - 2]
      } else if (this.queryParam.unitsn.split('  ').length > 1) {
        let arr = this.queryParam.unitsn.split('  ')
        this.queryParam.unitsn = arr[arr.length - 2]
      } else {
      }
      let record = this.dataSource[0]
      this.model = {}
      if (record) {
        this.model.line = record.line
        this.op = record.op
        this.selectedMainId = record.unitsn
      }
      this.loadData(1)
      //this.onSelectChange(record.federationId.split(','), [record])
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            //存储当前工站信息获取返工代码列表
            this.onSelectChange(record.federationId.split(','), [record])
          }
        }
      }
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.selectedMainId = ''
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.line = selectionRows[0].line
      this.op = selectionRows[0].op
      this.selectedMainId = selectionRows[0].unitsn

      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.onClearSelected()
      var params = this.getQueryParams()// 查询条件
      if (this.oneLoad === 1) {
        this.oneLoad = 2
      } else {
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.line = res.result.records[0].line
            this.ipagination.total = res.result.total
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      }
    },
    tabsChange(key) {
      this.tabsModel = key
      if (key === '2') {
        this.leftWidth = '100%'
        this.rightWidth = '0%'
      } else {
        this.leftWidth = '65%'
        this.rightWidth = '35%'
      }
    },
    cpnclick(item) {
      this.procDataMainId = item.recId
      if (item.result === '2') {
        this.isNok = true
      } else {
        this.isNok = false
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'woid', text: '工单ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'unitsn', text: '序列号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'partno', text: '产品或产品组', dictCode: '' })
      fieldList.push({ type: 'string', value: 'line', text: '产线或产线组', dictCode: '' })
      fieldList.push({ type: 'string', value: 'op', text: '工位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'stn', text: '工站', dictCode: '' })
      fieldList.push({ type: 'date', value: 'dt', text: '日期' })
      fieldList.push({ type: 'string', value: 'result', text: '9=Default,0=Loaded,1=OK,2=NOK', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'repeatCount', text: '重复加工次数', dictCode: '' })
      fieldList.push({
        type: 'string',
        value: 'status',
        text: '0: Init, 1: WIP, 2: FG, 3: Rework, 5: Scrap, 6:On Hold,7: InterFG,8: CheckPart',
        dictCode: ''
      })
      fieldList.push({ type: 'date', value: 'shiftDate', text: '班次日期' })
      fieldList.push({ type: 'string', value: 'shift', text: '班次', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwktoOp', text: '返工至工位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwktoStn', text: '返工至工站', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'cycleId', text: '运行周期ID', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'parttypeid', text: '产品ID', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'statusword', text: '状态字', dictCode: '' })
      fieldList.push({ type: 'string', value: 'segmentCode', text: '0:主线  1:1号支线 2:2号支线', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwkCode', text: '返工代码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'lotno', text: '是否成批', dictCode: '' })
      fieldList.push({ type: 'date', value: 'ctime', text: '更新时间' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.components-input-demo-size .ant-input {
  width: 80%;
  margin: 0 8px 8px 0;
}

/deep/ .ant-table-tbody .log-1 {
  background: #f39c12;
  color: #fff;
}

/deep/ .ant-table-tbody .log-2 {
  background: #f56954;
  color: #fff;
}

/deep/ .ant-table-tbody .log-3 {
  background: #00a65a;
  color: #fff;
}

</style>
